<?php
	
	class Devmod_method_castMultiLang extends Devmod_methods_abstraction {

		protected $after_operation = array(array(
										'for_method' => 'export', 
										'for_method_type' => 'frontend_list', 
										'use' => 'unserialize'
									), array(
										'for_method' => 'export',
										'for_method_type' => 'list',
										'use' => 'unserialize'
									), array(
										'for_method' => 'export',
										'for_method_type' => 'edit',
										'use' => 'unserialize_single'
									), array(
										'for_method' => 'save',
										'for_method_type' => 'edit',
										'use' => 'serialize'
									), array(
										'for_method' => 'save',
										'for_method_type' => 'add',
										'use' => 'serialize'
									), array(
										'for_method' => 'save',
										'for_method_type' => 'frontend_add',
										'use' => 'serialize'
									));
		
		public function set_config($args)
		{
			$multi_lang = array();
			
			foreach($args[0] as $key => $value)
			{
				$multi_lang[$value] = null;
			}
			
			$this->update_config('cast_multi_lang', $multi_lang);
		}

		
		public function serialize($args)
		{
			if(!isset($this->config[$this->type]['cast_multi_lang'])) return $args;
			
			$return = array();
			
			foreach($args as $key => $content)
			{
				if(is_array($content))
				{
					if(array_key_exists($key, $this->config[$this->type]['cast_multi_lang']))
					{
						$return[$key] = base64_encode(serialize($content));
					}	
				} else {
					$return[$key] = $content;
				}
			}
			return $return;
		}
		
		public function unserialize($args)
		{
			if(!isset($this->config[$this->type]['cast_multi_lang'])) return $args;
			
			$return = array(); $i = 0;
			
			foreach($args as $row)
			{
				foreach($row as $name => $content)
				{
					if(array_key_exists($name, $this->config[$this->type]['cast_multi_lang']))
					{
						$multi_parts = @unserialize(base64_decode($content));
						if($multi_parts === false)
						{
							$return[$i][$name] = $content;
						} else {
						
							if(isset($multi_parts[0])) continue;// fixed the bug with the empty array
							
							$return[$i][$name] = $multi_parts[$_SESSION['i18n']];
						}
					} else {
						$return[$i][$name] = $content;
					}
				} $i++;
			}
			
			return $return;
		}
		
		public function unserialize_single($args)
		{
			if(!isset($this->config[$this->type]['cast_multi_lang'])) return $args;
			
			$return = array();
			
			foreach($args as $key => $value)
			{
				if(array_key_exists($key, $this->config[$this->type]['cast_multi_lang']))
				{
					$return[$key] = @unserialize(base64_decode($value));
				} else {
					$return[$key] = $value;
				}
			}
			
			return $return;
		}

	}
